#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
解析验证码
"""

__author__ = 'hubert'

import tesserocr
from PIL import Image, ImageEnhance, ImageFilter
import pytesseract
import cv2

import py_baidu_ocr
import easyocr
# import PaddleOCR


# 验证码识别测试1，无法识别
# 路径/Users/hubert/Downloads/image.png 图片可以识别
def img_test1(img_path):
    image = Image.open(img_path)
    # image = Image.open("/Users/hubert/Downloads/image.png")
    print("demo1:", tesserocr.image_to_text(image))
    print("demo2:", pytesseract.image_to_string(image))


# 测试2
def img_test2(filename):
    image = cv2.imread(filename)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(filename, gray)
    text = pytesseract.image_to_string(Image.open(filename))
    # os.remove(filename)
    print(text)

# 推荐1
def img_test3(img_path):
    reader = easyocr.Reader(['ch_sim','en'], True)
    # 比较消耗性能
    result = reader.readtext(img_path)
    for i in result:
        word = i[1]
        print(word)
    print(result)




class img():
    # 采用二值化去除背景色,即仅保留黑、白两色。
    def pre_concert(self, img):
        width, height = img.size
        threshold = 30
        WHITE = (255, 255, 255)
        BLACK = (0, 0, 0)
        for i in range(0, width):
            for j in range(0, height):
                # 抽取坐标（i,j）出像素点的RGB颜色值
                p = img.getpixel((i, j))
                # print(p)#(255, 255, 255, 255)
                r, g, b = p
                if r > threshold or g > threshold or b > threshold:
                    # 设置坐标（i,j）处像素点的RGB颜色值为（255.255.255）
                    img.putpixel((i, j), WHITE)
                else:
                    img.putpixel((i, j), BLACK)
        print('二值化去除背景色')
        img.show()
        image_name = "/Users/hubert/Downloads/tmp/pre_fig.png"
        img.save(image_name)
        return self.noise_remove_pil(image_name, 4)

    from PIL import Image
    def noise_remove_pil(self,image_name, k):
        """
        8邻域降噪
        Args:
            image_name: 图片文件命名
            k: 判断阈值

        Returns:

        """

        def calculate_noise_count(img_obj, w, h):
            """
            计算邻域非白色的个数
            Args:
                img_obj: img obj
                w: width
                h: height
            Returns:
                count (int)
            """
            count = 0
            width, height = img_obj.size
            for _w_ in [w - 1, w, w + 1]:
                for _h_ in [h - 1, h, h + 1]:
                    if _w_ > width - 1:
                        continue
                    if _h_ > height - 1:
                        continue
                    if _w_ == w and _h_ == h:
                        continue
                    if img_obj.getpixel((_w_, _h_)) < 230:  # 这里因为是灰度图像，设置小于230为非白色
                        count += 1
            return count

        img = Image.open(image_name)
        # 灰度
        gray_img = img.convert('L')

        w, h = gray_img.size
        for _w in range(w):
            for _h in range(h):
                if _w == 0 or _h == 0:
                    gray_img.putpixel((_w, _h), 255)
                    continue
                # 计算邻域非白色的个数
                pixel = gray_img.getpixel((_w, _h))
                if pixel == 255:
                    continue

                if calculate_noise_count(gray_img, _w, _h) < k:
                    gray_img.putpixel((_w, _h), 255)
        gray_img_name='/Users/hubert/Downloads/tmp/noise_remove_pil.png'
        gray_img.save('/Users/hubert/Downloads/tmp/noise_remove_pil.png')
        print('降噪处理')
        gray_img.show()
        return self.jiangzao(gray_img_name)

    def jiangzao(self,gray_img_name):
        # 要去掉黑点，就是一个二值化降噪的过程。可以用PIL（Python Image Library）试试
        im = Image.open(gray_img_name)
        im = im.filter(ImageFilter.MedianFilter())
        enhancer = ImageEnhance.Contrast(im)
        im = enhancer.enhance(2)
        im = im.convert('1')
        im.save('/Users/hubert/Downloads/tmp/jiangzao.png')
        im.show()
        return self.ocr(im)

    # 传入图片进行识别
    def ocr(self,im):
        text = pytesseract.image_to_string(im, lang='eng')
        print(text)

# 识别验证码
if __name__ == '__main__':
    # 可识别
    path1 = "/Users/hubert/Downloads/image.png"
    # 不能识别
    path2 = "/Users/hubert/Downloads/pic/douban_captcha.jpeg"
    # 截图，有截图，不能识别中文
    path3 = "/Users/hubert/Downloads/iShot2022-03-02 16.50.02.png"

    # 可识别
    path4 = "/Users/hubert/Downloads/iShot2022-03-02 16.55.25.png"

    path5 = "/Users/hubert/Downloads/iShot2022-03-03 14.47.23.png"

    img_test1(path1)
    # img_test1(path2)
    # img_test1(path3)
    # img_test1(path4)
    # img_test1(path5)
    # 可以识别
    #result1 = py_baidu_ocr.baidu_ocr(path2)
    #print("下载本地识别:", result1)
    ## 可以识别
    #result2 = py_baidu_ocr.baidu_ocr(path5)
    #print("截图验证码进行识别:", result2)
    # 链接有时效性，不能识别，访问URL提示非法，采用下载本地方式进行识别
    path6 = "https://www.douban.com/misc/captcha?id=g9y57W4jJOHN0oW48ClYIPtE:en"
    result3 = py_baidu_ocr.baidu_ocr_url(path6)
    print("图片URL进行识别:", result3)
    print("解析结果", py_baidu_ocr.resolve_result(result3))

    """
    image1 = Image.open(path2)
    # a = np.asarray(image1)
    print(image1.mode)
    a = np.full((1, 1), 300)
    image1 = Image.fromarray(a, mode="RGB")
    # print("1", image1.getpixel((0, 0)))
    img = img()
    img.pre_concert(image1)
    """




